<template>
  <div>
    <van-sticky>
      <NavBar :show-left-arrow="false" left-text="" title="购物车"></NavBar>
    </van-sticky>

    <!-- 列表 -->
    <ul>
      <li v-for="item in list" :key="item.id">
        <van-checkbox v-model="item.checked" checked-color="#cea62a"></van-checkbox>
        {{ item.goods_name }} --- {{ item.retail_price }} -- {{ item.number }}
      </li>
    </ul>

    <div>
      <van-checkbox v-model="allChecked" checked-color="#cea62a">全选</van-checkbox>
      <div>总价：{{ totalPrice }}</div>
      <van-button @click="doSubmit">下单</van-button>
    </div>
  </div>
</template>
<script setup>
import NavBar from '../../components/NavBar.vue';
import { cartList as cartListApi } from '@/api/cart'
import { submitAction as submitActionApi } from '@/api/productDetail'
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router';
const router = useRouter()
const list = ref([])
onMounted(async () => {
  const res = await cartListApi({ openId: localStorage.getItem('openId') })
  res.data.forEach(item => item.checked = false)
  list.value = res.data
})

const allChecked = computed({
  get() {
    return list.value.every(item => item.checked)
  },
  set(val) {
    list.value.forEach(item => item.checked = val)
  }
})

const totalPrice = computed(() => {
  return list.value.reduce((total, current) => {
    if (current.checked) {
      return total + current.number * current.retail_price
    } else {
      return total
    }
  }, 0)
})


const doSubmit = async () => {
  const res = await submitActionApi({
    allPrise: totalPrice.value,
    goodsId: list.value.filter(item => item.checked).map(e => e.goods_id
    ).join(','),
    openId: localStorage.getItem('openId')
  })
  if (res.data === true) {
    // 跳转页面
    router.push({ name: 'Order' })
  }
}













</script>
<style lang="scss" scoped></style>